var mapMyPlace;
var pois = [];
var markersArray = [];
var infoWindow;

$(document).ready(function() {
	initializeMapMyPlace();
	initMarkerMyPlace();
	
	
	$(".tab_content").hide(); // Hide all content
	$("ul.tabs li:first").addClass("active").show(); // Activate first tab
	$(".tab_content:first").show(); // Show first tab content

	// On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active"); // Remove any "active" class
		$(this).addClass("active"); // Add "active" class to selected tab
		$(".tab_content").hide(); // Hide all tab content
		var activeTab = $(this).find("a").attr("href"); // Find the rel
		// attribute value to
		// identify the active
		// tab + content
		$(activeTab).fadeIn(); // Fade in the active content
		return false;
	});
	// quang nguyen
	// Action
	$(".tabs_content").hide(); // Hide all content
	$("ul.tabss li:first").addClass("active").show(); // Activate first tab
	$(".tabs_content:first").show(); // Show first tab content
	// Click Event
	$("ul.tabss li").click(function() {
		$("ul.tabss li").removeClass("active"); // Remove any "active" class
		$(this).addClass("active"); // Add "active" class to selected tab
		$(".tabs_content").hide(); // Hide all tab content
		var activeTab = $(this).find("a").attr("href"); // Find the rel
		// attribute value to
		// identify the active
		// tab + content
		$(activeTab).fadeIn(); // Fade in the active content
		return false;
	});
	
	
	$("#closeList").click(function() {
		//alert("day ");
		
		$("#listopen").hide();
		$("#closeList").hide();
		$("#place").hide();
		$("#openlist").show();
		//$("#map-canvas .gmnoprint:last").prev().css('margin-left', '20px');
		//$("#mylist").hide();
	});
	
	$("#openlist").click(function() {
		$("#listopen").show();
		$("#place").show();
		$("#openlist").hide();
		$("#closeList").show();
		//$("#map-canvas .gmnoprint:last").prev().css('margin-left', '490px');
		//$("#mylist").show();
	});

	$("#closeListMyPlace").click(function() {
		if ($("#listopen").is(':visible')) {
			$("#listopen").animate({
				width : 'hide'
			});
			$("#numberofplace").hide()
			$("#closeListMyPlace").hide();
			$("#openlist").show();
			// $("#pic").attr('src', 'images/right.png');
		} else {
			$("#listopen").animate({
				width : 'show'
			});
			$("#numberofplace").show()
			$("#closeListMyPlace").show();
			$("#openlist").hide();

			/*
			 * 
			 * $("#listopen").animate({ width : 'show' });
			 * $("#numberofplace").show() $("#closeListMyPlace").show();
			 * $("#openlist").show();
			 */
			// $("#pic").attr('src', 'images/left.png ');
		}
	});
});

function initMarkerEvent(marker, i) {
	google.maps.event.addListener(marker, 'rightclick', function(event) {
		showContextMenu(marker, event.latLng)
	});
	google.maps.event
			.addListener(
					marker,
					'mouseover',
					function(event) {
						var img = '<img src="' + marker.imgpath + '" width=100px height=100px />'

						var content = '<div id="same-place-panels" style="height: 110px; width: 250px; overflow: auto; margin-top:5px;">'
								+ '<div style="padding-left: 5px; float: left; width: 100px; height: 100px">'
								+ img
								+ '</div>'
								+ '<div style="margin-left: 110px;">'
								+ marker.address
								+ '<br>'
								+ marker.price
								+ '<br>' + '</div>' + '</div>';
						
						//infoWindow.open(mapMyPlace, marker);
						//infoWindow.setContent(content);
						
						var containerPixel = overlay.getProjection().fromLatLngToContainerPixel(event.latLng);
						var mapWidth = $('#map-canvas-myplace').width();
						var mapHeight = $('#map-canvas-myplace').height();
						var infoWidth = $('#info').width();
						var infoHeight = $('#info').height();
						var x = containerPixel.x;
						var y = containerPixel.y;
						
						var xmove=0;
						var ymove=0;
						
						if ((mapWidth - x) < infoWidth){
							x = x - infoWidth;
							xmove-=20
						}else{
							xmove+=20
						}
							
						if ((mapHeight - y) < infoHeight){
							y = y - infoHeight;
							//ymove-=20;
						}else{
							//y = y + infoHeight;
							//ymove+=20;
							//ymove+=infoHeight;
						}
						
						$('#info').html(content)
						$('#info').css({left : x+xmove,top : y+ymove});
						$('#info').show()
					});
	google.maps.event.addListener(marker, 'mouseout', function(event) {
		//infoWindow.close();
		$('#info').hide()
	});
}
function showContextMenu(marker, caurrentLatLng) {
	$("#info").hide();
	$('#rightclickMarker')
			.removeClass()
			.addClass('contextmenu')
			.html(
					""		/*
							+"<div style='background-color:red ; width:200px;height:80px;left:15px;position:absolute;'>"
							+ "<div id='edit' 	style='background-color:#ccc;color:red' class='context' onmouseover= 'onMouseInMarker(this)' onmouseout='onMouseOut (this)'>Edit place</div>"
							+ "<div id='delete' class='context'  onmouseover= 'onMouseInMarker(this) 'onMouseOutMarker (this)'>Delete place</div>"
							+ "<div id='detail' class='context'  onmouseover= 'onMouseInMarker(this) 'onMouseOutMarker (this)'>Show detail</div>"
							+"</div>"
							*/
							+"<div class='test' style='border:2px solid #bababa;background-color:white ; width:126px;height:79px;left:15px;position:absolute;'>"
							+ "<ul id='formPlace'><li id='Edit' onmouseover= 'onMouseInMarker(this)' onmouseout='onMouseOutMarker (this)' style='display: inline-block;height: 20px;width: 131px;position:absolute;margin-left:-5px;margin-top:4px;'><a href='#' style='color:black;text-decoration:none;padding: 3px 20px;font-size:15px' >Edit place</a><li>"
							+ "<li id='delete'  onmouseover= 'onMouseInMarker(this)' onmouseout='onMouseOutMarker (this)' style='display: inline-block;height: 20px;width: 131px;position:absolute;margin-left:-5px;margin-top:28px;'><a href='#' style='color:black;text-decoration:none;padding: 3px 20px;font-size:15px'>Delete place</a><li>"
							+ "<li id='show'  onmouseover= 'onMouseInMarker(this)' onmouseout='onMouseOutMarker (this)' style='display: inline-block;height: 20px;width: 131px;position:absolute;margin-left:-5px;margin-top:53px;'><a href='#' style='color:black;text-decoration:none;padding: 3px 20px;font-size:15px;bottom'>Show detail</a><li>"
							+ "</ul>"
							+"</div>"
				 );
	$('#rightclickMarker').find("#Edit").click(function() {
		$(location).attr('href', "editPlace?id=" + marker.id);
	})
	$('#rightclickMarker').find("#delete").click(function() {
		// var x;
		$("#contextmenu").hide();
		var r = confirm("Are you want delete place?");
		if (r == true) {
			$.ajax({
				url : "delete",
				type : "GET",
				data : "placeID=" + marker.id,
				success : function(response) {
				}
			});
			$("#"+marker.id).hide();
			marker.setMap(null);
			
		} else {
		}
		// document.getElementById("demo").innerHTML=x;
		// alert("Are you want delete place?");
		// alert(marker.id);
	})
	$('#rightclickMarker').find("#show").click(function() {
		showDetail(marker.id);
		//alert("deltail")
	})
	setMenuXY(caurrentLatLng);
}

function showDetail(id){
	$("#rightclickMarker").hide();
	$("#frmDetail").show();
	
	/*
	$("#imageplace").html('<img src="/Lemon/Avatar/getAvatar?placeID=' + id +  '" width=470px height=260px />')
	$.ajax({
		url : "placeDetail",
		type : "GET",
		data : "placeID="+id,
		success:function(response){
			var result = response;
			$("#addressValue").html(result.propertytype+"<br> Address: "+result.address+"<br> Description: "+result.description+"<br>Bed: "+result.bed+"<br> Bath: "+result.bath+"<br>Price: "+result.price);
			$("#contactplace").html(result.nameContact+"<br> Phone: "+result.phoneContact+"<br> Email: "+result.emailContact);
		}	
	});
	$.ajax({
		url : "listAllComment",
		type : 'GET',
		data : {
			placeid : id
		},
		contentType : "application/json; charset=utf-8",
		success : function(data) {
			var newest = $("#listAllOldComment");
			for (var i = 0; i < data.length; i++) {
				htmldata += data[i].userprofile.fullName + ": " + data[i].content + ';';				
				var divTempCM = "<div> " + data[i].userprofile.fullName + ":&nbsp;" + data[i].content + " <br></div>"
				$(newest).append(divTempCM);
			}
		},
		error : function(data) {
		}
	});
	*/
}


function closeDetail(){
	$("#frmDetail").hide()
}

function setMenuXY(caurrentLatLng) {
	var containerPixel = overlay.getProjection().fromLatLngToContainerPixel(
			caurrentLatLng);
	var mapWidth = $('#map-canvas-myplace').width();
	var mapHeight = $('#map-canvas-myplace').height();
	var menuWidth = $('#rightclickMarker').width();
	var menuHeight = $('#rightclickMarker').height();
	var x = containerPixel.x;
	var y = containerPixel.y;
	if ((mapWidth - x) < menuWidth)
		x = x - menuWidth;
	if ((mapHeight - y) < menuHeight)
		y = y - menuHeight;
	$('#rightclickMarker').css({
		left : x,
		top : y + 35
	}).fadeIn(200);
};

function onMouseInMarker(div) {
	div.style.background = "#0088cc";
}
function onMouseOutMarker(div) {
	//div.style.border = "none";
	div.style.background = "white";
}

// Load map in MyPlace
function initializeMapMyPlace() {
	infoWindow = new google.maps.InfoWindow();
	var center = new google.maps.LatLng(16.0713, 108.220304);
	var mapTypeIds = [];
	for ( var type in google.maps.MapTypeId) {
		mapTypeIds.push(google.maps.MapTypeId[type]);
	}
	var myOptions = {
		zoom : 15,
		center : center,
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		scaleControl : true,
		mapTypeControlOptions : {
			mapTypeIds : mapTypeIds
		}
	};
	mapMyPlace = new google.maps.Map(document.getElementById('map-canvas-myplace'), myOptions);
	geocoder = new google.maps.Geocoder();
	mapDiv = $('#map-canvas-myplace');
	contextMenu = $('#context-menu').appendTo(mapDiv);
	overlay = new google.maps.OverlayView();
	overlay.draw = function() {
	};
	overlay.setMap(mapMyPlace);
	// Hide context menu on several map events
	// google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
	// });
	google.maps.event.addListener(mapMyPlace, 'rightclick', function(e) {
		currentLatLng = e.latLng;
	});

	// Hide context menu on several map events
	$.each('click dragstart zoom_changed maptypeid_changed center_changed'
			.split(' '), function(i, name) {
		google.maps.event.addListener(mapMyPlace, name, function() {
			$('#rightclickMarker').fadeOut(200);
		});
	});
}
function initMarkerMyPlace() {
	var image = new google.maps.MarkerImage('http://nguyenlx.somee.com/marker.png',
		      // This marker is 20 pixels wide by 32 pixels tall.
		      new google.maps.Size(24, 38),
		      // The origin for this image is 0,0.
		      new google.maps.Point(0,0),
		      // The anchor for this image is the base of the flagpole at 0,32.
		      new google.maps.Point(0, 38));
	
	for ( var i = 0; i < pois.length; i++) {
		var position = new google.maps.LatLng(pois[i].lat, pois[i].lng);
		var marker = new google.maps.Marker({
			position : position,
			address : pois[i].address,
			price : pois[i].price,
			id : pois[i].id,
			imgpath : pois[i].imgpath,
			icon: image
		});
		initMarkerEvent(marker, i);
		markersArray.push(marker);
	}
	displayMarkersMyPlace();
}

function displayMarkersMyPlace() {
	var bounds = new google.maps.LatLngBounds();
	if (markersArray && markersArray.length > 0) {
		for ( var i = 0; i < markersArray.length; i++) {
			markersArray[i].setMap(mapMyPlace);
		}
	}
}
function initMarkerEventMyPlace(marker, i) {
	google.maps.event.addListener(marker, 'rightclick', function(event) {
		currentLatLng = event.latLng;
		currentMarker = this;
		showContextMenu(currentLatLng, i);
	});

	google.maps.event.addListener(marker, 'click', function(event) {
		/* if (this.getIcon() != dimIcon) { */
		// var content = '<div id="same-place-panels" style="height: 100px;
		// overflow: auto; margin-top:5px;"> City : '+ marker.title + ' </div>
		// ';
		// infoWindow.open(map, marker);
		// infoWindow.setContent(content);
		// alert(marker.id);
		// $(".superContainer").show();
	});

	google.maps.event.addListener(marker, 'mouseover', function() {
		/*
		 * $("#" + marker.id).css('color', '#DD8C01'); $("#" +
		 * marker.id).css('background-color', '#F3F0F0'); $("#" +
		 * marker.id).css('border', '2px solid gray');
		 * 
		 * var img = '<img src="' + marker.imgpath + '" width=100px
		 * height=100px />'
		 * 
		 * var content = '<div id="same-place-panels" style="height: 110px;
		 * width: 250px; overflow: auto; margin-top:5px;">' + '<div
		 * style="float: left; width: 100px; height: 100px">' + img + '</div>' + '<div
		 * style="margin-left: 110px;">' + marker.address + '<br>' +
		 * marker.price + '<br>' + '</div>' + '</div>'; infoWindow.open(map,
		 * marker); infoWindow.setContent(content);
		 */
		// alert("mouseover")
	});

	google.maps.event.addListener(marker, 'mouseout', function() {
		infoWindow.close();
		$("#" + marker.id).css('color', '#4587BA');
		$("#" + marker.id).css('background-color', '#fff');
		$("#" + marker.id).css('border', '1px solid gray');
	});

	google.maps.event.addListener(marker, 'dblclick', function(event) {
	});

	google.maps.event.addListener(map, "click", function(event) {

	});
}
function onMouseIn(elem) {
	elem.style.border = "2px solid gray";
	
	//elem.style.background = "red";
	//elem.style.width="126px";
	for ( var i = 0; i < markersArray.length; i++) {
		if (markersArray[i].id == (elem.id)) {
			markersArray[i].setAnimation(google.maps.Animation.BOUNCE);
		}
	}
}
function onMouseOut(elem) {
	elem.style.border = "1px solid gray";
	//elem.style.background = "white";
	for ( var i = 0; i < markersArray.length; i++) {
		if (markersArray[i].getAnimation() != null) {
			markersArray[i].setAnimation(null);
		}
	}
}
